<template>
  <el-dialog
    :title="d.title"
    custom-class="modal-treatment-drug-item"
    :append-to-body="true"
    v-model="d.isVisible"
    @close="closeDialog"
    width="1200px"
  >
    <el-form
      :rules="d.rules"
      :model="d.form"
      label-width="90px"
      ref="currentEditRef"
    >
      <el-form-item
        prop="medicineName"
        label="药物名称:"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]"
      >
        <xm-remote-select
          :disabled="d.isNotChangeMedine"
          v-model="d.form.drugId"
          :defaults="d.defaults"
          :itemList="d.itemList"
          @loadData="dtLoad"
          @seachData="querySearchDrugs"
          :isMultiple="false"
          :isFilterable="true"
          @change="handleSelectDrugs"
        ></xm-remote-select>
      </el-form-item>
      <el-row>
        <el-col :span="9">
          <el-form-item prop="usage" label="用法:">
            <el-select
              size="default"
              clearable
              v-model="d.form.usage"
              @change="handleUsgeChange"
            >
              <el-option
                :key="item.termChs"
                :value="item.termChs"
                v-for="item in usages"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="drugSpec" label="规格/剂型:">
            {{ d.form.spec }}/{{ d.form.dosageForm }}
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="unit" label="单位:">
            {{ d.form.unit }}
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 急性恶化界面 -->
      <template v-if="!d.form.areas">
        <el-row class="emergencyUseUsage">
          <el-col :span="24">
            <!-- <el-col class="action-bk-title" :span="2"></el-col> -->
            <el-col :span="6">
              <el-form-item prop="emergencyUseUsage" label="单次用量">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.emergencyUseUsage"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="emergencyUseFrequency" label="频次">
                <el-select
                  size="default"
                  clearable
                  v-model="d.form.emergencyUseFrequency"
                >
                  <el-option
                    :key="item.termChs"
                    :value="item.termLatin"
                    v-for="item in frequencys"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="d.form.emergencyUseFrequency === '自定义'">
              <el-form-item prop="emergencyUseCustom" label="自定义">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.emergencyUseCustom"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="emergencyUseRemark" label="备注">
                <el-input
                  size="default"
                  v-model="d.form.emergencyUseRemark"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="areas" label="选择区域:">
              <gradeCheckbox
                :disabled="d.notChangeAera"
                title="全选"
                :options="areaData"
                v-model="d.form.areas"
              ></gradeCheckbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="绿区:" v-if="d.form.areas.includes('绿区')">
          <el-row>
            <!-- <el-col class="action-bk-title" :span="2">绿区:</el-col> -->
            <el-col :span="6">
              <el-form-item prop="greenUsage" label="单次用量">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.greenUsage"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="greenFrequency" label="频次">
                <el-select
                  size="default"
                  clearable
                  v-model="d.form.greenFrequency"
                >
                  <el-option
                    :key="item.termChs"
                    :value="item.termLatin"
                    v-for="item in frequencys"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="d.form.greenFrequency === '自定义'">
              <el-form-item prop="greenCustom" label="自定义">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.greenCustom"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="greenRemark" label="备注">
                <el-input
                  size="default"
                  v-model="d.form.greenRemark"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="黄区:" v-if="d.form.areas.includes('黄区')">
          <el-row>
            <!-- <el-col class="action-bk-title" :span="2">黄区:</el-col> -->
            <el-col :span="6">
              <el-form-item prop="yellowUsage" label="单次用量">
                <el-input clearable v-model="d.form.yellowUsage"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="yellowFrequency" label="频次">
                <el-select
                  size="default"
                  clearable
                  v-model="d.form.yellowFrequency"
                >
                  <el-option
                    :key="item.termChs"
                    :value="item.termLatin"
                    v-for="item in frequencys"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="d.form.yellowFrequency === '自定义'">
              <el-form-item prop="yellowCustom" label="自定义">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.yellowCustom"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="yellowRemark" label="备注">
                <el-input
                  size="default"
                  v-model="d.form.yellowRemark"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="红区:" v-if="d.form.areas.includes('红区')">
          <el-row v-if="d.form.areas.includes('红区')">
            <!-- <el-col class="action-bk-title" :span="2">红区:</el-col> -->
            <el-col :span="6">
              <el-form-item prop="redUsage" label="单次用量">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.redUsage"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="redFrequency" label="频次">
                <el-select
                  size="default"
                  clearable
                  v-model="d.form.redFrequency"
                >
                  <el-option
                    :key="item.termChs"
                    :value="item.termLatin"
                    v-for="item in frequencys"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="d.form.redFrequency === '自定义'">
              <el-form-item prop="redCustom" label="自定义">
                <el-input
                  clearable
                  size="default"
                  v-model="d.form.redCustom"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="redRemark" label="备注">
                <el-input size="default" v-model="d.form.redRemark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="newDrugTableItem(d.form)" type="primary">
        保存
      </el-button>
      <el-button @click="d.isVisible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { reactive, ref, toRefs } from 'vue'
  import { searchList } from '@/api/modules/medicinal'
  import emr from '@/hooks/emr'
  import XmRemoteSelect from 'XMC/XmRemoteSelect'
  import { isHas } from '../../../../utils/validate'
  import { buildUUID } from '@/utils/uuid.js'

  export default {
    name: 'addMedicalRecord',
    components: { XmRemoteSelect },
    emits: ['addMedical', 'update:modelValue'],
    setup(props, context) {
      const initData = function (
        type,
        notChangeAera,
        isNotChangeMedine,
        data,
        isVisible = true
      ) {
        /**
         * 1. 从哪个区进来 默认选该区
         * 2. 简易版直接显示红区 根据isSample. 标准版 分有颜色 无颜色 急性发作
         * 3. 编辑不给换区
         * type:行动计划列表展示分组. data:传入其中的数据 isVisible:弹窗是否展示
         */
        d.isVisible = isVisible
        d.title = '添加药物'
        // 不许改变分区
        d.notChangeAera = notChangeAera
        // 不许修改药品
        d.isNotChangeMedine = isNotChangeMedine

        // 调用该数据的
        d.type = type
        // 拿到外面的索引
        if (data && isHas(data.index)) d.index = data.index
        if (type.includes('usage')) d.title = '添加按需使用药物'
        if (type.includes('emergencyUse')) d.title = '当前急性发作缓解治疗方案'
        if (type.includes('cnUse')) d.title = '中医治疗方案'
        // 关于自动选区的代码
        switch (type) {
          case 'actionGreen':
          case 'usageGreen':
            d.form.areas.push('绿区')
            break
          case 'actionYellow':
          case 'usageYellow':
            d.form.areas.push('黄区')
            break
          case 'actionRed':
          case 'usageRed':
            d.form.areas.push('红区')
            break
          case 'emergencyUse':
          case 'cnUse':
            d.form.areas = null
            break
          default:
            break
        }
        if (data) {
          const {
            medicineName,
            singleDosage,
            frequency,
            custom,
            drugId,
            remark,
            spec,
            dosageForm,
            usage,
            unit,
            uuid,
            commonName,
          } = data
          // 配置默认显示
          d.defaults = { label: medicineName, value: drugId }
          // 公用界面渲染
          d.form.medicineName = medicineName
          d.form.drugId = drugId
          d.form.spec = spec
          d.form.dosageForm = dosageForm
          d.form.usage = usage
          d.form.unit = unit
          d.form.commonName = commonName
          // 没有传入区 说明是应急区
          if (d.form.areas === null) {
            d.form.emergencyUseUsage = singleDosage
            d.form.emergencyUseFrequency = frequency
            d.form.emergencyUseCustom = custom
            d.form.emergencyUseRemark = remark
            // 保存当前进来药物的uuid
            d.form.emergencyUUID = uuid
          } else {
            if (d.form.areas.includes('黄区')) {
              d.form.yellowUsage = singleDosage
              d.form.yellowFrequency = frequency
              d.form.yellowCustom = custom
              d.form.yellowRemark = remark
              d.form.yellowUUID = uuid
            } else if (d.form.areas.includes('红区')) {
              d.form.redUsage = singleDosage
              d.form.redFrequency = frequency
              d.form.redCustom = custom
              d.form.redRemark = remark
              d.form.redUUID = uuid
            } else if (d.form.areas.includes('绿区')) {
              d.form.greenUsage = singleDosage
              d.form.greenFrequency = frequency
              d.form.greenCustom = custom
              d.form.greenRemark = remark
              d.form.greenUUID = uuid
            }
          }
        }
      }
      // 方法
      const handleSelectDrugs = function (id) {
        const item = d.itemList.find((item) => item.value === id).data
        d.form.medicineName = item.medicineName
        d.form.commonName = item.commonName
        d.form.spec = item.spec
        d.form.dosageForm = item.dosageForm
        d.form.unit = item.unit
        d.form.drugId = item.id
        d.form.usage = item.usage
      }
      const querySearchDrugs = async function (obj, cb) {
        if (!obj.val) return
        const res = await searchList({ name: obj.val })
        d.itemList = res.data.map((item, index) => {
          return {
            value: item.id,
            // eslint-disable-next-line max-len
            label: `${item.medicineName}(通用名:${item.commonName}) 规格:${item.spec} 剂型:${item.dosageForm}`,
            data: item,
          }
        })
        // cb(res.data)
      }

      const dtLoad = async function (cb) {
        // d.itemList = [
        //   // { value: '心火上炎证(ZZXU20)', label: '心火上炎证(ZZXU20)' },
        //   // { value: '心脾积热，循经上炎证(ZZXP41)', label: '心脾积热，循经上炎证(ZZXP41)' },
        //   // { value: '相火上炎证(ZZSU30)', label: '相火上炎证(ZZSU30)' },
        // ]
        cb()
      }
      const handleUsgeChange = function () {
        console.log('handleUsgeChange')
      }
      const newDrugTableItem = function () {
        currentEditRef.value.validate((valid) => {
          if (valid) {
            save()
            d.isVisible = false
          }
        })
      }

      const closeDialog = function () {
        // 清除数据
        // currentEditRef.value.resetFields()
        d.form = initForm()
        d.type = null
        d.index = null
        d.defaults = {}
        currentEditRef.value.resetFields()
      }
      const save = function () {
        const spec = d.form.spec
        const dosageForm = d.form.dosageForm
        const usage = d.form.usage
        const unit = d.form.unit
        const red =
          d.form.areas && d.form.areas.includes('红区')
            ? {
                medicineName: d.form.medicineName,
                commonName: d.form.commonName,
                singleDosage: d.form.redUsage,
                frequency:
                  d.form.redFrequency === '自定义'
                    ? d.form.redCustom
                    : d.form.redFrequency,
                custom: d.form.redCustom,
                drugId: d.form.drugId,
                remark: d.form.redRemark,
                spec,
                dosageForm,
                usage,
                unit,
                uuid: d.form.redUUID ? d.form.redUUID : buildUUID(),
              }
            : null
        const yellow =
          d.form.areas && d.form.areas.includes('黄区')
            ? {
                medicineName: d.form.medicineName,
                commonName: d.form.commonName,
                singleDosage: d.form.yellowUsage,
                frequency:
                  d.form.yellowFrequency === '自定义'
                    ? d.form.yellowCustom
                    : d.form.yellowFrequency,
                custom: d.form.yellowCustom,
                drugId: d.form.drugId,
                remark: d.form.yellowRemark,
                spec,
                dosageForm,
                usage,
                unit,
                uuid: d.form.yellowUUID ? d.form.yellowUUID : buildUUID(),
              }
            : null
        const green =
          d.form.areas && d.form.areas.includes('绿区')
            ? {
                medicineName: d.form.medicineName,
                commonName: d.form.commonName,
                singleDosage: d.form.greenUsage,
                frequency:
                  d.form.greenFrequency === '自定义'
                    ? d.form.greenCustom
                    : d.form.greenFrequency,
                custom: d.form.greenCustom,
                drugId: d.form.drugId,
                remark: d.form.greenRemark,
                spec,
                dosageForm,
                usage,
                unit,
                uuid: d.form.greenUUID ? d.form.greenUUID : buildUUID(),
              }
            : null

        const emergencyUse = !d.form.areas
          ? {
              medicineName: d.form.medicineName,
              commonName: d.form.commonName,
              singleDosage: d.form.emergencyUseUsage,
              frequency:
                d.form.emergencyUseFrequency === '自定义'
                  ? d.form.emergencyUseCustom
                  : d.form.emergencyUseFrequency,
              custom: d.form.emergencyUseCustom,
              drugId: d.form.drugId,
              remark: d.form.emergencyUseRemark,
              spec,
              dosageForm,
              usage,
              unit,
              uuid: d.form.emergencyUUID ? d.form.emergencyUUID : buildUUID(),
            }
          : null
        const tmp = {
          red,
          green,
          yellow,
          isColor: d.title === '添加药物',
          type: d.type,
          index: d.index,
        }
        // 中医和急性都用这个
        if (d.type === 'emergencyUse' || d.type === 'cnUse') {
          tmp[d.type] = emergencyUse
        }
        context.emit('addMedical', tmp)
      }
      // 初始化
      const initForm = function () {
        return {
          medicineName: null, // 药品名称
          greenFrequency: null, // 绿区频次
          greenUsage: null, // 单次用量
          greenRemark: null, // 绿区备注
          greenCustom: null,
          greenUUID: null,
          yellowUsage: null,
          yellowFrequency: null,
          yellowRemark: null,
          yellowCustom: null,
          yellowUUID: null,
          redUsage: null,
          redFrequency: null,
          redRemark: null,
          redCustom: null,
          redUUID: null,
          emergencyUseUsage: null,
          emergencyUseFrequency: null,
          emergencyUUID: null,
          usage: null, // 用法
          spec: null, //规格
          dosageForm: null, //剂型
          drugId: null, // 药品ID
          // drugSpec: null, // 规格/剂型 规格
          // drugForm: null, // 规格/剂型 剂型
          packagingUnit: null, // 单位
          areas: [], // 选择区域
          type: null,
          index: null,
        }
      }

      const rule1 = [
        {
          required: true,
          message: '请完善选项',
          trigger: 'change',
          isVisible: false,
        },
      ]
      const rules = {
        medicineName: rule1, // 药品名称
        greenFrequency: rule1, // 绿区频次
        greenUsage: rule1, // 绿区用量
        // greenRemark: rule1, // 绿区备注
        greenCustom: rule1, //绿区自定义
        yellowUsage: rule1,
        yellowFrequency: rule1,
        // yellowRemark: rule1,
        yellowCustom: rule1,
        redUsage: rule1,
        redFrequency: rule1,
        // redRemark: rule1,
        redCustom: rule1,
        emergencyUseUsage: rule1,
        emergencyUseFrequency: rule1,
        emergencyUseCustom: rule1,
        usage: rule1, // 用法
        areas: [{ required: true, message: '请选择区域', trigger: 'blur' }], // 选择区域
      }
      const currentEditRef = ref(null)
      const areaData = [
        { id: '绿区', menuName: '绿区' },
        { id: '黄区', menuName: '黄区' },
        { id: '红区', menuName: '红区' },
      ]
      const d = reactive({
        form: initForm(),
        notChangeAera: false,
        isNotChangeMedine: false,
        rules,
        isVisible: false,
        title: '添加药物',
        isType: null,
        itemList: [],
        defaults: [],
      })
      return {
        currentEditRef,
        d,
        areaData,
        // isVisible,
        handleSelectDrugs,
        handleUsgeChange,
        newDrugTableItem,
        querySearchDrugs,
        closeDialog,
        initData,
        dtLoad,
        ...toRefs(emr()),
      }
    },
  }
</script>
<style lang="scss" scoped>
  .modal-treatment-drug-item {
    .el-dialog__header {
      .el-dialog__title {
        font-size: 14px !important;
      }
    }

    .action-bk-title {
      text-align: right;
      line-height: 40px;
      font-size: 18px;
    }

    .emergencyUseUsage {
      .el-col {
        display: inline-block;
      }
    }
  }
</style>
